package com.example.xuwsh.redis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: xuwsh
 * @Date: 2023/04/21/21:56
 * @Description:
 */
public class XuwshRedisConfig {
    public JedisPool[] jedisPools = new JedisPool[0];

    public XuwshRedisConfig() {
    }

    /**
     * redis的url
     */
    public String redisHost;
    /**
     * 端口号
     */
    public Integer port;
    /**
     * 密码
     */
    public String password;
    /**
     * 最大连接数
     */
    public Integer maxIdle;
    /**
     * 最小连接数
     */
    public Integer minIdle;
    /**
     * 操作超时时间
     */
    public Integer timeout;

    public String getRedisHost() {
        return redisHost;
    }

    public Integer getPort() {
        return port;
    }

    public String getPassword() {
        return password;
    }

    public void setRedisHost(String redisHost) {
        this.redisHost = redisHost;
    }

    public void setPort(Integer port) {
        this.port = port;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Integer getMaxIdle() {
        return maxIdle;
    }

    public void setMaxIdle(Integer maxIdle) {
        this.maxIdle = maxIdle;
    }

    public Integer getMinIdle() {
        return minIdle;
    }

    public void setMinIdle(Integer minIdle) {
        this.minIdle = minIdle;
    }

    public Integer getTimeout() {
        return timeout;
    }

    public void setTimeout(Integer timeout) {
        this.timeout = timeout;
    }

    public void getRedisConfig() {
        // 设置jedis连接池配置
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxIdle(maxIdle);
        poolConfig.setMinIdle(minIdle);
        // 生成连接池
        List<JedisPool> jedisPoolList = new ArrayList<JedisPool>();
        jedisPoolList.add(new JedisPool(poolConfig, redisHost, port, timeout, password));

        jedisPools = jedisPoolList.toArray(jedisPools);
    }

    /**
     * 实现jedis连接的获取和释放，具体的redis业务逻辑由executor实现
     *
     * @param executor RedisExecutor接口的实现类
     * @return
     */
    public <T> T execute(String key, XuwshRedisExecutor<T> executor) {

        Jedis jedis = jedisPools[(0x7FFFFFFF & key.hashCode()) % jedisPools.length].getResource();
        T result = null;
        try {
            result = executor.execute(jedis);
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        return result;
    }
}
